package org.richin.servlet.Filter.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

public class FilterChainFilter implements Filter {

    private List<Filter> filters = new ArrayList<Filter>();
    private List<Filter> extensionFilters = new ArrayList<Filter>();
	public void destroy() {
		   for (Filter filter : this.extensionFilters) filter.destroy();
           for (Filter filter : filters) filter.destroy();
		
	}
	  private void doBeforeProcessing(RequestWrapper request, ResponseWrapper response)
      throws IOException, ServletException {

  }
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//doBeforeProcessing(request, response);
		 if (filters.size() == 0  && this.extensionFilters.size() == 0) {
             chain.doFilter(request, response);
     } else {
             List<Filter> filters = new ArrayList<Filter>(this.filters);
             if (this.extensionFilters.size() > 0) filters.addAll(this.extensionFilters);
             new SubChain(chain, filters).doFilter(request, response);
     }
		
	}

	public void init(FilterConfig cfg) throws ServletException {


        for (Filter filter : filters) filter.init(cfg);
        for (Filter filter : this.extensionFilters) filter.init(cfg);
     
		
	}

}
